//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CommunityServer.Blogs.Components;
using CommunityServer.Blogs.Controls;
using CommunityServer.Components;
using CommunityServer.ControlPanel.UI;
using CommunityServer.Controls;
using TWC = Telligent.Web.UI;
using Calendar = ComponentArt.Web.UI.Calendar;
using ResourceManager = CommunityServer.ControlPanel.Components.ResourceManager;
using ResourceLinkButton = CommunityServer.ControlPanel.Controls.ResourceLinkButton;

namespace CommunityServer.ControlPanel.Blogs
{
	/// <summary>
	///		Summary description for Skin_CreateEditBlogPost.
	/// </summary>
	public class CreateEditBlogPost : BaseBlogControl
	{
        #region Controls
		protected TWC.TabbedPanes EditorTabs;
		protected Controls.ResourceControl Message;
		protected ResourceLinkButton PostButton;
		protected ResourceLinkButton SaveButton;
		protected ResourceLinkButton SaveEditButton;
		protected Literal PreviewTitle;
		protected Literal PreviewBody;
		protected HtmlGenericControl ErrorPanel;
		protected HtmlGenericControl Post;
		protected HtmlGenericControl Preview;
		protected TextBox PostSubject;
		protected Editor PostBody;
		protected TextBox postName;
		protected TextBox postExcerpt;
		protected RegularExpressionValidator vRegexPostName;
        protected RequiredFieldValidator postSubjectValidator;
        protected RequiredFieldValidator postBodyValidator;
        protected ValidationSummary valSummary;
		protected CommentModerationDropDownList ModerationDDL;
		protected TextBox postDate;
		protected Label DateError;
        protected Calendar DatePicker;
        protected DropDownRange HourPicker;
        protected DropDownRange MinutePicker;
        protected DropDownList AMPM;
        protected HtmlInputHidden ServeruploadtempID;
		protected HtmlInputHidden Serverfriendlyfilename;
        protected Label serverfilename;
		protected System.Web.UI.Control RemoveAttachment;
        protected FeedbackNotificationDropDownList NotificationType;
		protected System.Web.UI.HtmlControls.HtmlTableRow CrossPostingRow;
        protected TextBox VideoUrl;
        protected TextBox VideoImageUrl;
        protected TextBox VideoDuration;
		protected TextBox VideoWidth;
		protected TextBox VideoHeight;
		protected TagEditor Tags;
		protected HtmlContainerControl DefaultTagsContainer;
		protected Literal DefaultTags;

        #endregion

		#region Field / Properties

        protected Modal Modal1;
		protected Script Script1;
		protected CSContext context = CSContext.Current;
		protected InkWebControl inkWeb = null;
		protected CommunityServer.Controls.Script Script2;
		protected System.Web.UI.HtmlControls.HtmlGenericControl ButtonSet;
		protected CheckBox EnableInk = null;
        

        protected bool EnableAttachments
        {
            get
            {
                return Permissions.ValidatePermissions(this.CurrentWeblog,Permission.LocalAttachment, context.User) || Permissions.ValidatePermissions(this.CurrentWeblog,Permission.RemoteAttachment, context.User);
            }
        }

		protected bool EnableInkSupport
		{
			get
			{
				return context.SiteSettings.EnableInk && context.User.EnableInk && Permissions.ValidatePermissions(this.CurrentWeblog,Permission.Ink, context.User);
			}
		}

        protected bool EnableVideos
        {
            get
            {
                return Permissions.ValidatePermissions(this.CurrentWeblog,Permission.Video, context.User);
            }
        }
		#endregion

		override protected void OnInit(EventArgs e)
		{
			this.PostButton.Click += new System.EventHandler(this.PostButton_Click);
			this.SaveButton.Click +=new EventHandler(SaveButton_Click);
			this.SaveEditButton.Click +=new EventHandler(SaveEditButton_Click);
			this.Load += new System.EventHandler(this.Page_Load);
			base.OnInit(e);
		}


		private void Page_Load(object sender, EventArgs e)
		{
            AjaxManager.Register(this,"CreateEditBlogPost");
			this.PanelPage.IsInEdit = true;
			UI.PanelPage.RegisterControlForByPass(PostButton);
			UI.PanelPage.RegisterControlForByPass(SaveButton);
			UI.PanelPage.RegisterControlForByPass(SaveEditButton);

			if(EnableInk != null)
				EnableInk.Text = ResourceManager.GetString("CP_Blogs_CreateEditBlogPost_EnableInk"); 

           
			if (!Page.IsPostBack)
			{
				Bind();
			}

		}

        const int attachTabIndex = 1;
        const int inkTabIndex = 3;
        const int videoTabIndex = 2;

		void Bind()
		{
            
			EditorTabs.Panes[attachTabIndex].Visible = this.EnableAttachments;
//            EditorTabs.Tabs[5].Visible = false;
//            EditorTabs.Tabs[4].Visible = false;
//            SaveEditButton.Visible = false;
            if(this.EnableInkSupport)
            {
                inkWeb.Enabled = true;
                inkWeb.RegisterLinkButton(this.PostButton);
            }
            else
            {
                inkWeb.Enabled = false;
            }
			EditorTabs.Panes[inkTabIndex].Visible = inkWeb.Enabled;
			CrossPostingRow.Visible = WeblogConfiguration.Instance().EnableCrossPosting;
            
			vRegexPostName.ValidationExpression = WeblogPosts.PostNamePattern;
			vRegexPostName.ErrorMessage = ResourceManager.GetString("Weblog_CreateEditBlogPost_PostNameRegexValidator");
            postSubjectValidator.ErrorMessage = ResourceManager.GetString("Weblog_CreateEditBlogPost_TitleValidator");
            postBodyValidator.ErrorMessage = ResourceManager.GetString("Weblog_CreateEditBlogPost_BodyValidator");
            valSummary.HeaderText = ResourceManager.GetString("Weblog_CreateEditBlogPost_ValidatorSummary");
            
            EditorTabs.Panes[videoTabIndex].Visible = this.EnableVideos;
            bool hasMultipleOwners = CurrentWeblog.OwnerArray.Length > 1;
  
			if (context.PostID > 0)
			{
				WeblogPost post = WeblogPosts.GetPost(context.PostID, true, false, false);
				if (post != null)
				{
					if(post.HasInk)
					{
						if(inkWeb.Enabled)
						{
							InkData ink = Ink.Get(post.InkID);
							if(ink != null)
							{
								inkWeb.InkData = ink.InkString;
							}
						}
					}

					PopulateCategories(post.BlogPostType);

					PostSubject.Text = Server.HtmlDecode(post.Subject);
					PostBody.Text = post.Body;
					postExcerpt.Text = post.Excerpt;
					ModerationDDL.Items.FindByValue(post.ModerationType.ToString()).Selected = true;
					postName.Text = post.Name;
                    SetDate(post.UserTime);
					NotificationType.SelectedValue = post.FeedbackNotificationType;
                    VideoUrl.Text = post.VideoUrl;
                    VideoImageUrl.Text = post.VideoImageUrl;
                    VideoDuration.Text = post.VideoDuration;
					VideoHeight.Text = post.VideoHeight >= 0 ? post.VideoHeight.ToString() : string.Empty;
					VideoWidth.Text = post.VideoWidth >= 0 ? post.VideoWidth.ToString() : string.Empty;

					if (post.HasCategories)
						Tags.SelectedTags = post.Categories;

                    if(!Globals.IsNullorEmpty(post.AttachmentFilename))
                    {
                        PostAttachmentMetaData attachment = post.Attachment;
                        if(attachment != null)
                        {
                            this.Serverfriendlyfilename.Value = attachment.FileName;
							this.ServeruploadtempID.Value = "Existing";
							this.serverfilename.Text = attachment.FileName;
                        }
                    }
					
					SetYesNo(post.PostConfig, post.IsApproved, !post.IsLocked, post.EnableAllOwnerNotification, post.EnableRatings, post.EnableTrackBacks, hasMultipleOwners, post.EnableCrossPosting);

				}
			}
			else
			{
				PopulateCategories(this.BlogPostType);
                SetDate(UserTime.CurrentUserTime);
				ModerationDDL.Items.FindByValue(CurrentWeblog.ModerationTypeDefault.ToString()).Selected = true;
				NotificationType.SelectedValue = CurrentWeblog.FeedbackNotificationType;
                SetYesNo(CurrentWeblog.DefaultPostConfig, true, true, this.CurrentWeblog.EnableAllOwnerNotification, this.CurrentWeblog.EnableRatingsDefault, CurrentWeblog.EnableTrackbacksDefault, hasMultipleOwners, CurrentWeblog.EnableCrossPostingDefault);
			}

			// Display Default Tags notice if that feature is being used on this site
			WeblogConfiguration config = WeblogConfiguration.Instance();
			if (config.DefaultAggregateTags != null && config.DefaultAggregateTags.Length > 0)
			{
				DefaultTagsContainer.Visible = true;
				foreach (string tag in config.DefaultAggregateTags)
				{
					if (DefaultTags.Text.Length > 0)
						DefaultTags.Text += "; ";

					DefaultTags.Text += tag;
				}
			}
			else
			{
				DefaultTagsContainer.Visible = false;
			}


    	}

		#region Get Post From Form
		private WeblogPost GetPostFromForm()
		{
			WeblogPost post = null;

			if (context.PostID > 0)
			{
				post = WeblogPosts.GetPost(context.PostID, false, false, false);
                
				if(Globals.IsNullorEmpty(this.ServeruploadtempID.Value))
					PostAttachments.Delete(context.PostID);
			}
			else
			{
				post = new WeblogPost();
				post.Username = context.User.Username;
				post.SectionID = CurrentWeblog.SectionID;
				post.ParentID = 0;
				post.BlogPostType = this.BlogPostType;
				post.PostID = -1;
				post.IsApproved = false;
			}
			
			if(EnableInkSupport)
			{
				if(EnableInk.Checked)
				{
					if(!post.HasInk)
					{
						if(!Globals.IsNullorEmpty(inkWeb.InkData))
						{
							post.InkID = CreateInk();
						}
					}
					else
					{
						if(Globals.IsNullorEmpty(inkWeb.InkData))
						{
							DeleteInk(post);
							post.InkID = -1;
						}
						else
						{
							InkData existingInk = Ink.Get(post.InkID);
							existingInk.InkString = inkWeb.InkData;
							Ink.Update(existingInk);
						}
					}


				}
				else
				{
					if(post.HasInk)
					{
						DeleteInk(post);
						post.InkID = -1;
					}
				}
			}
			

			post.Subject = PostSubject.Text;
			post.Name = postName.Text;
			post.Excerpt = postExcerpt.Text;
			post.Body = PostBody.Text;
			post.PostType = PostContentType.HTML;
			post.FormattedBody = null;

			post.SetPostMedia(PostMediaType.Video, false);
			if(this.EnableVideos)
			{
				post.VideoDuration = this.VideoDuration.Text;
				post.VideoImageUrl = this.VideoImageUrl.Text;
				post.VideoUrl = this.VideoUrl.Text;
				
				if (this.VideoHeight.Text.Length > 0)
					post.VideoHeight = int.Parse(this.VideoHeight.Text);

				if (this.VideoWidth.Text.Length > 0)
					post.VideoWidth = int.Parse(this.VideoWidth.Text);

				if (post.VideoUrl.Trim().Length > 0)
					post.SetPostMedia(PostMediaType.Video, true);
			}

			PopulateFromYesNo(post);

			post.Categories = Tags.SelectedTags;

			post.ModerationType = (CommentModerationType) Enum.Parse(typeof (CommentModerationType), ModerationDDL.SelectedValue, false);


			post.UserTime = GetDate();
			post.PostDate = UserTime.ConvertToServerTime(post.UserTime);
			post.FeedbackNotificationType = NotificationType.SelectedValue;

			return post;
	
		}

		#endregion 


		private void SaveButton_Click(object sender, EventArgs e)
		{
			SaveAndReturn(false);
		}

		private void SaveEditButton_Click(object sender, EventArgs e)
		{
			if (!Page.IsValid)
				return;

			WeblogPost post = GetPostFromForm();

			int postID = -1;
			BlogPostResults result = SavePost(post,out postID);

			if (result == BlogPostResults.Success)
			{
				Response.Redirect(BlogUrls.Instance().PostEditor(this.CurrentWeblog.SectionID,postID));
			}
			else
			{
				SetError(result);
			}

		}


		private void PostButton_Click(object sender, EventArgs e)
		{
			SaveAndReturn(true);
		}

		private void SaveAndReturn(bool isPublished)
		{
			if (!Page.IsValid)
				return;
	
			WeblogPost post = GetPostFromForm();
			post.IsApproved = isPublished;
	
			int postID = -1;
			BlogPostResults result = SavePost(post,out postID);
	
			if (result == BlogPostResults.Success)
			{
				if(post.BlogPostType == BlogPostType.Post)
					Response.Redirect("postlist.aspx?tab=postlist&sectionid=" + CurrentWeblog.SectionID.ToString());
				else
					Response.Redirect("articlelist.aspx?tab=articlelist&sectionid=" + CurrentWeblog.SectionID.ToString());
			}
			else
			{
				SetError(result);
			}
		}

		private void SetError(BlogPostResults result)
		{
			ResourceControl Message = FindControl("Message") as ResourceControl;
			Message.ResourceName = result == BlogPostResults.DuplicationName ? "Weblog_Exception_DuplicatePostName" : "Weblog_Exception_DuplicatePostBody";
			ErrorPanel.Visible = true;
		}

		private BlogPostResults SavePost(WeblogPost post, out int postID)
		{
		
			BlogPostResults result = BlogPostResults.Success;

			postID = context.PostID;

			if (postID > 0)
			{
				result = WeblogPosts.Update(post);
			}
			else
			{
				
				result = WeblogPosts.Add(post, context.User, out postID);
			}

			if (result == BlogPostResults.Success)
			{
				SaveUpdateAttachment(postID, post);
			}

			return result;

		}

		private void SaveUpdateAttachment(int postID, WeblogPost post)
		{
			if(!Globals.IsNullorEmpty(ServeruploadtempID.Value) && ServeruploadtempID.Value != "Existing")
			{
				WeblogAttachmentSettings fs = WeblogConfiguration.Instance().AttachmentSettings;
				Guid g = new Guid(ServeruploadtempID.Value);
				PostAttachment pa = PostAttachments.ToggleTemporary(g,this.Serverfriendlyfilename.Value, !fs.EnableDataStoreStorage, postID,this.CurrentWeblog.SectionID,context.User.UserID);

                    
				if(fs.EnableFileSystemStorage)
				{
					if(pa != null && !pa.IsRemote)
						fs.SaveAttachmentToDisk(pa,this.CurrentWeblog.SectionID ,postID);
				}
			}
	
			PostCategories.ExpireCategoryCache(post.SectionID);
		}

		[AjaxMethod(IncludeControlValuesWithCallBack=false)]
        public string PreviewPost(string text)
        {
            WeblogPost post = new WeblogPost();
            post.Body = text;
            post.Subject = "";
            post.BlogPostType = this.BlogPostType;
            post.SectionID = this.CurrentWeblog.SectionID;

            WeblogPosts.PreviewFormat(post);
            return post.FormattedBody;
        }

	
		#region Private Helpers

		private void SetDate(DateTime dt)
		{
			DatePicker.SelectedDate = dt;
			int h = dt.Hour;
			if(h == 0)
			{
				h=12;
				AMPM.SelectedIndex = 0;
			}
			else if (h == 12)
			{
				AMPM.SelectedIndex = 1;
			}
			else if(h > 12)
			{
				h = h-12;
				AMPM.SelectedIndex = 1;
			}
			HourPicker.SetSelected(h);
			MinutePicker.SetSelected(dt.Minute);
			//AMPM.Items.FindByValue(dt.ToString("tt",System.Globalization.CultureInfo.InvariantCulture)).Selected = true;
		}

		private DateTime GetDate()
		{
			int minute = MinutePicker.GetSelected;
			int hour = HourPicker.GetSelected;
			if(AMPM.SelectedValue == "AM")
			{
				if(hour == 12)
					hour = 0;
			}
			else
			{
				if(hour != 12)
					hour += 12;
			}

			return new DateTime(DatePicker.SelectedDate.Year,DatePicker.SelectedDate.Month,DatePicker.SelectedDate.Day,hour,minute,0);
		}

		private void PopulateCategories(BlogPostType bpt)
		{
			Tags.AvailableTags = PostCategories.GetCategories(this.CurrentWeblog.SectionID, true, true);
		}

		private bool GetYesNo(string ynID)
		{
			return (FindControl(ynID) as YesNoRadioButtonList).SelectedValue;
		}

		private void PopulateFromYesNo(WeblogPost post)
		{
			bool isPost = this.BlogPostType == BlogPostType.Post;
			post.EnableAllOwnerNotification = GetYesNo("ynNotifyAllOwners");
			post.IsLocked = !GetYesNo("ynEnableReplies");
			//post.IsApproved = GetYesNo("ynPublished");
			post.EnableRatings = GetYesNo("ynEnableRatings");
			post.EnableTrackBacks = GetYesNo("ynEnableTrackBacks");
			post.EnableCrossPosting = GetYesNo("ynEnableCrossPosting");

			if (isPost)
			{
				post.IsAggregated = GetYesNo("ynAggregatePost");
				post.IsCommunityAggregated = GetYesNo("ynCommunity");
				post.SyndicateExcerpt = GetYesNo("ynSyndicateExcerpt");
			}

		}

		private void EnableYesNo(string ynID, bool Selected, bool enable)
		{
			YesNoRadioButtonList yn = FindControl(ynID) as YesNoRadioButtonList;
			if (yn != null)
			{
				yn.SelectedValue = Selected;

				if (!enable)
					FindControl(ynID + "_row").Visible = false;
			}
		}

		private void SetYesNo(BlogPostConfig bc, bool isPublished, bool allowReplies, bool notifyAllOwners, bool rate, bool track, bool hasMultipleOwners, bool crosspost)
		{
			bool isPost = this.BlogPostType == BlogPostType.Post;
			EnableYesNo("ynEnableReplies", allowReplies, true);
			EnableYesNo("ynNotifyAllOwners", notifyAllOwners, hasMultipleOwners);
			//EnableYesNo("ynPublished", isPublished, true);
			EnableYesNo("ynAggregatePost", PostConfigHelper.IsPostConfigSelected(bc, BlogPostConfig.IsAggregated), isPost);
			EnableYesNo("ynCommunity", PostConfigHelper.IsPostConfigSelected(bc, BlogPostConfig.IsCommunityAggregated), isPost);
			EnableYesNo("ynSyndicateExcerpt", PostConfigHelper.IsPostConfigSelected(bc, BlogPostConfig.SyndicateExcerpt), isPost);
			EnableYesNo("ynEnableRatings", rate, true);
			EnableYesNo("ynEnableTrackBacks", track, true);
			EnableYesNo("ynEnableCrossPosting", crosspost, true);

		}

		private int CreateInk()
		{
			InkData newInk = new InkData();
			newInk.ApplicationType = ApplicationType.Weblog;
			newInk.DateUpdated = DateTime.Now;
			newInk.InkString = inkWeb.InkData;
			newInk.SectionID = CurrentWeblog.SectionID;
			newInk.UserID = context.User.UserID;
			return Ink.Add(newInk);
		}

		private void InitializeComponent()
		{
		
		}

		private void DeleteInk(WeblogPost post)
		{
			InkData deletedInk = new InkData();
			deletedInk.InkID = post.InkID;
			deletedInk.SectionID = CurrentWeblog.SectionID;
	
			Ink.Delete(deletedInk);
		}

		#endregion


	}

}
